package com.kye.express.business.jd.shop;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.util.Pair;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.GsonUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.jd.goods_all_category.JDAllCategoryActivity;
import com.kye.express.business.jd.goods_detail.JDGoodsDetailActivity;
import com.kye.express.business.jd.goods_list_by_category.JDGoodsListByCategoryActivity;
import com.kye.express.business.jd.search_list.search.JDGoodsSearchActivity;
import com.kye.express.business.jd.shop.model.JDGoodsCategoryModel;
import com.kye.express.business.jd.shop.model.JDGoodsItemModel;
import com.kye.express.business.jd.shop.model.JDIntegralModel;
import com.kye.express.business.jd.shop.model.JDTitleModel;
import com.kye.express.business.jd.shop.viewbinder.JDCategoryViewBinder;
import com.kye.express.business.jd.shop.viewbinder.JDGoodsViewBinder;
import com.kye.express.business.jd.shop.viewbinder.JDInegralViewBinder;
import com.kye.express.business.jd.shop.viewbinder.JDTitleViewBinder;
import com.kye.express.databinding.ActivityJdShopBinding;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.user.User;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

public class JDShopActivity extends BaseToolbarActivity implements JDShopConstract.JDShopView, JDCategoryViewBinder.OnCategoryItemListener, JDGoodsViewBinder.OnGoodsItemListener {

    private JDShopConstract.JDShopPresenter presenter;
    private ActivityJdShopBinding binding;
    private User userInfo;
    private MultiTypeAdapter adapter;

    public static void startActivity(Context context) {
        checkLogin(context, new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(context, JDShopActivity.class);
                context.startActivity(intent);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_jd_shop);
        presenter = new JDShopConstract.JDShopPresenter();
        initToolbar(savedInstanceState);
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    private void initToolbar(Bundle savedInstanceState) {
        ToolbarManager.setToolbar(this, binding.toolbar);
    }

    private void initViews(Bundle savedInstanceState) {
        adapter = new MultiTypeAdapter();
        adapter.register(JDIntegralModel.class, new JDInegralViewBinder());
        adapter.register(JDTitleModel.class, new JDTitleViewBinder());
        adapter.register(JDGoodsCategoryModel.class, new JDCategoryViewBinder(this));
        adapter.register(JDGoodsItemModel.class, new JDGoodsViewBinder(this));
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                Object item = adapter.getItems().get(position);
                if (item instanceof JDIntegralModel) {
                    return 4;
                } else if (item instanceof JDTitleModel) {
                    return 4;
                } else if (item instanceof JDGoodsCategoryModel) {
                    return 1;
                } else {
                    return 2;
                }
            }
        });
        binding.homeList.setLayoutManager(gridLayoutManager);
        binding.homeList.setAdapter(adapter);
    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(binding.llErrorServer.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorNet.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llEmpty.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.goodsSearch)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        JDGoodsSearchActivity.startActivity();
                    }
                });
        binding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                presenter.refresh(userInfo);
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                presenter.loadmore(userInfo);
            }

        });
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                presenter.refreshInit(userInfo);
            }
        });
    }

    private void initData(Bundle savedInstanceState) {
        presenter.bind(this);
    }

    @Override
    public void onUser(User user) {
        userInfo = user;
        binding.statusLayout.showLoadingView();
    }

    @Override
    public void refreshInitSuccess(Pair<List<Object>, Boolean> datas) {
        binding.statusLayout.showContentView();
        binding.refreshLayout.setEnableLoadmore(datas.second);
        adapter.setItems(datas.first);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void refreshInitServerError(Throwable e) {
        binding.statusLayout.showErrorServerView();
        ToastManager.show(getBaseContext(), e.getMessage());
    }

    @Override
    public void refreshInitNetError(Throwable e) {
        binding.statusLayout.showErrorNetworkView();
        ToastManager.show(getBaseContext(), e.getMessage());
    }

    @Override
    public void refreshSuccess(Pair<List<Object>, Boolean> datas) {
        Logger.d("refreshSuccess\n" + GsonUtils.toJsonString(datas.first, true));
        binding.refreshLayout.finishRefresh(true);
        binding.refreshLayout.setEnableLoadmore(datas.second);
        adapter.setItems(datas.first);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void refreshServerError(Throwable e) {
        binding.refreshLayout.finishRefresh(false);
        ToastManager.show(getBaseContext(), e.getMessage());
    }

    @Override
    public void refreshNetError(Throwable e) {
        binding.refreshLayout.finishRefresh(false);
        ToastManager.show(getBaseContext(), e.getMessage());
    }

    @Override
    public void loadmoreSuccess(Pair<List<Object>, Boolean> listBooleanPair) {
        binding.refreshLayout.finishLoadmore(true);
        binding.refreshLayout.setEnableLoadmore(listBooleanPair.second);
        List<Object> items = (List<Object>) adapter.getItems();
        int startPosition = items.size();
        items.addAll(listBooleanPair.first);
        adapter.notifyItemRangeInserted(startPosition, listBooleanPair.first.size());
    }

    @Override
    public void loadmoreServerError(Throwable e) {
        binding.refreshLayout.finishLoadmore(false);
        ToastManager.show(getBaseContext(), e.getMessage());
    }

    @Override
    public void loadmoreNetError(Throwable e) {
        binding.refreshLayout.finishLoadmore(false);
        ToastManager.show(this, e.getMessage());
    }

    @Override
    public void onCategoryItemClicked(JDGoodsCategoryModel item) {
        Logger.d("onCategoryItemClicked :\n " + GsonUtils.toJsonString(item, true));
        if (item.getCategoryBean() != null) {
            JDIntegralModel jdIntegralModel = (JDIntegralModel) adapter.getItems().get(0);
            JDGoodsListByCategoryActivity.startActivity(this, item.getCategoryBean(), jdIntegralModel.getIntegralUserBean().getExchangeRate());
        } else {
            JDIntegralModel jdIntegralModel = (JDIntegralModel) adapter.getItems().get(0);
            JDAllCategoryActivity.startActivity(JDShopActivity.this, jdIntegralModel.getIntegralUserBean().getExchangeRate());
        }
    }

    @Override
    public void onGoodsItemClicked(JDGoodsItemModel item) {
        JDGoodsDetailActivity.startActivity(this, item.getGoodsItemBean());
    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoaded() {

    }

    @Override
    public MultiTypeAdapter getAdapter() {
        return adapter;
    }
}
